﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using Beyond;

public class ProjectBuilder {
    private static BEUnity.Platform platform = BEUnity.Platform.Unknow;
    private static bool useMono = false;
    private static string[] scenes;

    public static void Build() {
        Debug.Log("[ProjectBuilder] " + System.Environment.CurrentDirectory);
        parseArgs();

        buildAssetBundles();

        prepareScenes();
        buildScenes();
    }

    private static void parseArgs() {
        Debug.Log("【参数解析】");
        UnityHelper.InitEnvironment();
        foreach (string arg in System.Environment.GetCommandLineArgs()) {
            if (!arg.StartsWith("eArg-")) {
                continue;
            }
            if (arg.EndsWith("-android")) {
                platform = BEUnity.Platform.Android;
            } else if (arg.EndsWith("-ios")) {
                platform = BEUnity.Platform.Ios;
            }
            if (arg.EndsWith("-mono")) {
                useMono = true;
            }
        }
        Debug.Log("  发布平台：" + platform);
    }

    private static void buildAssetBundles() {
        Debug.Log("【编译AssetBundle】");
        switch (platform) {
            case BEUnity.Platform.Android:
                AssetBundleBuilder.BuildAssetBundles(AssetBundleManager.GetEditorOutputPath(platform), BuildTarget.Android);
                break;
            case BEUnity.Platform.Ios:
                AssetBundleBuilder.BuildAssetBundles(AssetBundleManager.GetEditorOutputPath(platform), BuildTarget.iOS);
                break;
        }
    }

    private static void prepareScenes() {
        Debug.Log("【场景准备】");
        string _scenes = "    ";
        List<string> names = new List<string>();
        foreach (EditorBuildSettingsScene s in EditorBuildSettings.scenes) {
            if (s != null && s.enabled) {
                names.Add(s.path);
            }
        }
        scenes = names.ToArray();
        foreach (string s in scenes) {
            _scenes += s + " ";
        }
        Debug.Log(_scenes);
    }

    private static void buildScenes() {
        Debug.Log("【编译场景】");

        string projectName = Application.dataPath.Replace("\\", "/");
        projectName = projectName.Substring(0, projectName.LastIndexOf("/"));
        projectName = projectName.Substring(projectName.LastIndexOf("/") + 1);

        PlayerSettings.companyName = "zj";
        PlayerSettings.productName = projectName;
        PlayerSettings.applicationIdentifier = "com." + PlayerSettings.companyName + "." + projectName.ToLower();
        //PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, "宏定义");//宏定义的设置
        if (platform == BEUnity.Platform.Android) {
            PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.Android, PlayerSettings.applicationIdentifier);
#if UNITY_2018_4
            EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
            PlayerSettings.scriptingRuntimeVersion = ScriptingRuntimeVersion.Latest;
            PlayerSettings.SetApiCompatibilityLevel(BuildTargetGroup.Android, ApiCompatibilityLevel.NET_Standard_2_0);
            if (useMono) {
                PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android, ScriptingImplementation.Mono2x);
                PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARMv7;
                PlayerSettings.SetManagedStrippingLevel(BuildTargetGroup.Android, ManagedStrippingLevel.Disabled);
            } else {
                PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android, ScriptingImplementation.IL2CPP);
                PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARMv7 | AndroidArchitecture.ARM64;
                PlayerSettings.SetManagedStrippingLevel(BuildTargetGroup.Android, ManagedStrippingLevel.Low);
            }
#elif UNITY_2018_2
            EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.Gradle;
            PlayerSettings.SetApiCompatibilityLevel(BuildTargetGroup.Android, ApiCompatibilityLevel.NET_2_0_Subset);
            PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android, ScriptingImplementation.Mono2x);
            PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARMv7;
            PlayerSettings.strippingLevel = StrippingLevel.Disabled;
#else // 5.6.4
            EditorUserBuildSettings.androidBuildSystem = AndroidBuildSystem.ADT;
            PlayerSettings.SetApiCompatibilityLevel(BuildTargetGroup.Android, ApiCompatibilityLevel.NET_2_0_Subset);
            PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android, ScriptingImplementation.Mono2x);
            PlayerSettings.Android.targetDevice = AndroidTargetDevice.ARMv7;
            PlayerSettings.strippingLevel = StrippingLevel.UseMicroMSCorlib;
#endif
            BuildPipeline.BuildPlayer(scenes, "proj.android/unity", BuildTarget.Android, BuildOptions.AcceptExternalModificationsToPlayer);
            EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Standalone, BuildTarget.StandaloneWindows);
        } else if (platform == BEUnity.Platform.Ios) {
            PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.iOS, PlayerSettings.applicationIdentifier);
            //PlayerSettings.SetScriptingBackend(BuildTargetGroup.iOS, ScriptingImplementation.IL2CPP);
            //PlayerSettings.SetApiCompatibilityLevel(BuildTargetGroup.iOS, ApiCompatibilityLevel.NET_2_0_Subset);
            PlayerSettings.stripEngineCode = true;
            PlayerSettings.iOS.targetDevice = iOSTargetDevice.iPhoneAndiPad;
            PlayerSettings.SetArchitecture(BuildTargetGroup.iOS, 1);
            PlayerSettings.iOS.targetOSVersionString = "8.0";
            bool showSplash = PlayerSettings.SplashScreen.show;
            PlayerSettings.SplashScreen.show = false;
            EditorUserBuildSettings.symlinkLibraries = true;
            PlayerSettings.SetApplicationIdentifier(BuildTargetGroup.iOS, PlayerSettings.applicationIdentifier);
            BuildPipeline.BuildPlayer(scenes, "proj.ios", BuildTarget.iOS, BuildOptions.AcceptExternalModificationsToPlayer | BuildOptions.SymlinkLibraries);
#if UNITY_2018
            EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Standalone, BuildTarget.StandaloneOSX);
#else // 5.6.4
            EditorUserBuildSettings.SwitchActiveBuildTarget(BuildTargetGroup.Standalone, BuildTarget.StandaloneOSXIntel64);
#endif
            PlayerSettings.SplashScreen.show = showSplash;

            XcodeProjectProcessor.update();
        }
    }


    [MenuItem("Assets/Diidon Update %#u")]
    public static void UpdateProject() {
        //EditorUtility.DisplayProgressBar("项目更新", "更新中...", 0.10f);
        Debug.Log("【项目更新】");
        //Debug.Log(Application.dataPath);
        string sdk4utRoot = Application.dataPath + "/../../DiidonSdk4UT";
        if (!Directory.Exists(sdk4utRoot)) {
            int i = Application.dataPath.IndexOf("DiidonSdk4UT");
            if (i > 0) {
                sdk4utRoot = Application.dataPath.Substring(0, i + 12);
            }
        }
        if (!Directory.Exists(sdk4utRoot)) {
            Debug.Log("    未找到DiidonSdk4UT");
            //EditorUtility.ClearProgressBar();
            return;
        }
        //Debug.Log(sdk4utRoot);
        copy(sdk4utRoot + "/Plugins/ios", Application.dataPath + "/Plugins");
        if (sdk4utRoot.IndexOf(":") > 0) {
            if (BEUnity.version == BEUnity.Version.v5_6_4) {
                copy(sdk4utRoot + "/prebuilt/win32/Debug", Application.dataPath + "/Plugins/x86");
            } else {
                copy(sdk4utRoot + "/prebuilt/win32/Debug", Application.dataPath + "/Plugins/x86_64");
            }
        } else {
            copy(sdk4utRoot + "/prebuilt/mac", Application.dataPath + "/Plugins/mac");
        }
        //EditorUtility.ClearProgressBar();
    }

    private static void copy(string src, string dest) {
        foreach (string srcFile in Directory.GetFiles(src, "*", SearchOption.AllDirectories)) {
            string destFile = dest + srcFile.Substring(src.Length);
            if (File.Exists(destFile) && File.GetLastWriteTime(srcFile) <= File.GetLastWriteTime(destFile)) {
                continue;
            }
            Debug.Log(destFile);
            DirectoryInfo dir = Directory.GetParent(destFile);
            if (!dir.Exists) {
                dir.Create();
            }
            File.Copy(srcFile, destFile, true);
        }
    }
}

public class AssetBundleBuilder {
    [MenuItem("Assets/Build AssetBundles %#l")]
    static void BuildAllAssetBundles() {
        UnityHelper.InitEnvironment();
        Debug.Log("【资源打包】 for " + BEUnity.platform);
        switch (BEUnity.platform) {
            case BEUnity.Platform.Windows:
                BuildAssetBundles(AssetBundleManager.GetEditorOutputPath(BEUnity.platform), BuildTarget.StandaloneWindows);
                break;
            case BEUnity.Platform.OsX:
                BuildAssetBundles(AssetBundleManager.GetEditorOutputPath(BEUnity.platform), BuildTarget.StandaloneOSX);
                break;
            default:
                Debug.Log("  平台" + BEUnity.platform + "不支持编辑器中打包");
                break;
        }
    }

    public static void BuildAssetBundles(string savePath, BuildTarget target) {
        if (!Directory.Exists(savePath)) {
            Directory.CreateDirectory(savePath);
        }
        BuildPipeline.BuildAssetBundles(savePath, BuildAssetBundleOptions.None, target);
    }
}

//[InitializeOnLoad]
//class ProjectLoadListener {

//    static ProjectLoadListener() {
//        Debug.Log("ProjectLoadListener");
//        ProjectBuilder.UpdateProject();
//    }

//}